package com.example.springaidemo.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;

import com.example.springaidemo.model.ChatMessage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BailianService {

    private final RestTemplate restTemplate;
    private final String apiKey;
    private final String apiUrl;
    private final String model;
    private final Double temperature;
    private final Integer maxTokens;
    private final boolean enabled;

    public BailianService(
            RestTemplate restTemplate,
            @Value("${spring.ai.bailian.api-key}") String apiKey,
            @Value("${spring.ai.bailian.base-url}") String baseUrl,
            @Value("${spring.ai.bailian.chat.options.model}") String model,
            @Value("${spring.ai.bailian.chat.options.temperature}") Double temperature,
            @Value("${spring.ai.bailian.chat.options.maxTokens}") Integer maxTokens,
            @Value("${spring.ai.bailian.enabled:false}") boolean enabled) {
        this.restTemplate = restTemplate;
        this.apiKey = apiKey;
        this.apiUrl = baseUrl + "/chat/completions";
        this.model = model;
        this.temperature = temperature;
        this.maxTokens = maxTokens;
        this.enabled = enabled;
    }

    public String generateContent(String prompt) {
        // 检查百炼大模型是否启用
        if (!enabled) {
            return "百炼大模型未启用，请在application.properties中设置spring.ai.bailian.enabled=true";
        }
        
        // 创建HTTP头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey);

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", model);
        requestBody.put("temperature", temperature);
        requestBody.put("max_tokens", maxTokens);
        
        // 创建消息列表
        Map<String, String> message = new HashMap<>();
        message.put("role", "user");
        message.put("content", prompt);
        requestBody.put("messages", List.of(message));

        // 创建HTTP实体
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送请求并获取响应
        try {
            // 使用String作为响应类型，但配置RestTemplate不自动解析JSON
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(apiUrl, requestEntity, String.class);
            String responseBody = responseEntity.getBody();
            
            // 直接返回响应内容，不尝试自动解析
            return responseBody != null ? responseBody : "空响应";
        } catch (Exception e) {
            return "API调用错误: " + e.getMessage();
        }
    }

    public String chat(String message) {
        // 对于聊天场景，与生成内容使用相同的方法
        return generateContent(message);
    }

    // 多轮对话方法
    public String chatWithHistory(String message, List<ChatMessage> history) {
        // 检查百炼大模型是否启用
        if (!enabled) {
            return "百炼大模型未启用，请在application.properties中设置spring.ai.bailian.enabled=true";
        }
        
        // 创建HTTP头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey);

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", model);
        requestBody.put("temperature", temperature);
        requestBody.put("max_tokens", maxTokens);
        
        // 创建消息列表，包含历史消息和新消息
        List<Map<String, String>> messages = new ArrayList<>();
        
        // 添加历史消息
        if (history != null) {
            for (ChatMessage chatMessage : history) {
                Map<String, String> msg = new HashMap<>();
                msg.put("role", chatMessage.getRole());
                msg.put("content", chatMessage.getContent());
                messages.add(msg);
            }
        }
        
        // 添加新消息
        Map<String, String> newMessage = new HashMap<>();
        newMessage.put("role", "user");
        newMessage.put("content", message);
        messages.add(newMessage);
        
        requestBody.put("messages", messages);

        // 创建HTTP实体
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送请求并获取响应
        try {
            // 使用String作为响应类型，但配置RestTemplate不自动解析JSON
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(apiUrl, requestEntity, String.class);
            String responseBody = responseEntity.getBody();
            
            // 直接返回响应内容，不尝试自动解析
            return responseBody != null ? responseBody : "空响应";
        } catch (Exception e) {
            return "API调用错误: " + e.getMessage();
        }
    }
}